/**
 * DFCM数据库通用操作脚本
 * 用于处理dfcmdata数据库的表浏览和数据查看功能
 */

// 全局变量 - 使用dfcm前缀避免与其他模块变量冲突
let dfcmCurrentTable = '';
let dfcmCurrentPage = 0;
let dfcmCurrentSize = 20;
let dfcmCurrentSort = '';
let dfcmCurrentDirection = 'asc';
let dfcmCurrentKeyword = '';
let dfcmTableColumns = {};
let dfcmTablePages = {};

// 添加缓存对象
let dfcmCache = {
    tables: null,
    columns: {},
    primaryKeys: {},
    data: {}
};

// 添加用于取消请求的控制器
let dfcmAbortController = null;

// 添加节流定时器
let dfcmThrottleTimer = null;

/**
 * 加载DFCM数据库表列表
 * @param {boolean} forceRefresh - 是否强制刷新数据，不使用缓存
 */
function loadDfcmTables(forceRefresh = false) {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 如果有缓存且不强制刷新，则使用缓存
    if (!forceRefresh && dfcmCache.tables) {
        renderDfcmTableList(dfcmCache.tables);
        console.log('使用缓存加载表列表');
        return;
    }
    
    // 取消之前的请求
    cancelPendingRequests();
    
    // 创建新的AbortController
    dfcmAbortController = new AbortController();
    const signal = dfcmAbortController.signal;
    
    // 获取所有表名
    fetch(`${API_BASE}/dfcmdata/tables`, { signal })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.statusText);
            }
            return response.json();
        })
        .then(tables => {
            // 缓存表列表
            dfcmCache.tables = tables;
            
            // 渲染表格
            renderDfcmTableList(tables);
        })
        .catch(error => {
            // 忽略取消请求的错误
            if (error.name === 'AbortError') {
                console.log('表列表请求已取消');
                return;
            }
            
            console.error('加载表列表失败:', error);
            showMessage('加载DFCM数据库表列表失败: ' + error.message, 'error');
            mainContent.innerHTML = '<div class="error-container">加载失败，请刷新重试</div>';
        });
}

/**
 * 取消所有正在进行的请求
 */
function cancelPendingRequests() {
    if (dfcmAbortController) {
        dfcmAbortController.abort();
        dfcmAbortController = null;
    }
}

/**
 * 渲染DFCM数据库表列表
 */
function renderDfcmTableList(tables) {
    const mainContent = document.getElementById('mainContent');
    
    // 分类表（按前缀或类型）
    const tableGroups = groupTables(tables);
    
    // 构建HTML
    let html = `
        <div class="content-header">
            <h1>DFCM数据库表管理</h1>
            <div class="header-actions">
                <div class="search-box">
                    <input type="text" id="tableSearchInput" placeholder="搜索表名..." onkeyup="filterTables()">
                    <button onclick="filterTables()"><i class="fa fa-search"></i></button>
                </div>
            </div>
        </div>
        <div class="content-body">
            <div class="table-list-container">
    `;
    
    // 为每个分组创建折叠面板
    Object.keys(tableGroups).forEach(groupName => {
        const groupTables = tableGroups[groupName];
        
        html += `
            <div class="table-group">
                <div class="table-group-header" onclick="toggleTableGroup(this)">
                    <i class="fa fa-folder"></i>
                    <span>${groupName} (${groupTables.length})</span>
                    <i class="fa fa-angle-down"></i>
                </div>
                <div class="table-group-content">
                    <ul class="table-list">
        `;
        
        // 添加每个表的链接
        groupTables.forEach(table => {
            html += `
                <li class="table-item" data-table-name="${table}">
                    <a href="javascript:void(0)" onclick="throttledLoadTableData('${table}')">
                        <i class="fa fa-table"></i>
                        <span>${table}</span>
                    </a>
                </li>
            `;
        });
        
        html += `
                    </ul>
                </div>
            </div>
        `;
    });
    
    html += `
            </div>
            <div class="table-data-container" id="tableDataContainer">
                <div class="empty-selection">
                    <i class="fa fa-database fa-3x"></i>
                    <p>请从左侧选择一个表查看数据</p>
                </div>
            </div>
        </div>
    `;
    
    mainContent.innerHTML = html;
    
    // 默认展开第一个分组
    const firstGroup = document.querySelector('.table-group-header');
    if (firstGroup) {
        firstGroup.classList.add('active');
        firstGroup.nextElementSibling.style.display = 'block';
    }
}

/**
 * 节流函数，防止短时间内频繁加载表数据
 */
function throttledLoadTableData(tableName, page = 0, size = 20, sort = '', direction = 'asc', keyword = '') {
    // 取消之前的定时器
    if (dfcmThrottleTimer) {
        clearTimeout(dfcmThrottleTimer);
    }
    
    // 如果用户点击的是当前已加载的表，且参数未变化，则无需重新加载
    if (tableName === dfcmCurrentTable && 
        page === dfcmCurrentPage && 
        size === dfcmCurrentSize && 
        sort === dfcmCurrentSort && 
        direction === dfcmCurrentDirection && 
        keyword === dfcmCurrentKeyword) {
        return;
    }
    
    // 设置新的定时器，300ms后执行操作
    dfcmThrottleTimer = setTimeout(() => {
        loadTableData(tableName, page, size, sort, direction, keyword);
    }, 300);
}

/**
 * 将表按前缀或用途分组
 */
function groupTables(tables) {
    const groups = {};
    
    tables.forEach(table => {
        // 根据表名前缀分组
        let groupName = '其他';
        
        if (table.startsWith('micircuit_')) {
            groupName = '微电路';
        } else if (table.startsWith('discrete_')) {
            groupName = '分立器件';
        } else if (table.startsWith('tube_')) {
            groupName = '电子管';
        } else if (table.startsWith('variable_')) {
            groupName = '可变元件';
        } else if (table.startsWith('capacitor_')) {
            groupName = '电容器';
        } else if (table.startsWith('rpcount_')) {
            groupName = 'RP计数';
        } else if (table.startsWith('smt_')) {
            groupName = '表面贴装';
        } else if (table.startsWith('connector_')) {
            groupName = '连接器';
        } else if (table.startsWith('part_')) {
            groupName = '零部件';
        } else if (table.startsWith('rp299c_') || table.startsWith('rp108a_')) {
            groupName = 'RP标准';
        } else if (table.includes('database') || table.includes('sql') || table.includes('sys')) {
            groupName = '系统表';
        }
        
        // 创建组（如果不存在）
        if (!groups[groupName]) {
            groups[groupName] = [];
        }
        
        // 添加表到组
        groups[groupName].push(table);
    });
    
    // 对每个组内的表按字母顺序排序
    Object.keys(groups).forEach(group => {
        groups[group].sort();
    });
    
    return groups;
}

/**
 * 切换表分组的展开/折叠
 */
function toggleTableGroup(header) {
    header.classList.toggle('active');
    const content = header.nextElementSibling;
    content.style.display = content.style.display === 'block' ? 'none' : 'block';
}

/**
 * 过滤表列表
 */
function filterTables() {
    const searchInput = document.getElementById('tableSearchInput');
    const keyword = searchInput.value.toLowerCase();
    const tableItems = document.querySelectorAll('.table-item');
    
    tableItems.forEach(item => {
        const tableName = item.getAttribute('data-table-name').toLowerCase();
        if (tableName.includes(keyword)) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
    
    // 显示/隐藏分组
    const tableGroups = document.querySelectorAll('.table-group');
    tableGroups.forEach(group => {
        const visibleItems = group.querySelectorAll('.table-item[style=""]').length;
        if (visibleItems === 0) {
            group.style.display = 'none';
        } else {
            group.style.display = '';
            // 展开有可见项的分组
            if (keyword) {
                const header = group.querySelector('.table-group-header');
                const content = group.querySelector('.table-group-content');
                header.classList.add('active');
                content.style.display = 'block';
            }
        }
    });
}

/**
 * 生成缓存键
 */
function generateCacheKey(tableName, page, size, sort, direction, keyword) {
    return `${tableName}_${page}_${size}_${sort}_${direction}_${keyword}`;
}

/**
 * 加载表数据
 * @param tableName
 * @param page
 * @param size
 * @param sort
 * @param direction
 * @param keyword
 * @param {boolean} forceRefresh - 是否强制刷新数据，不使用缓存
 */
function loadTableData(tableName, page = 0, size = 20, sort = '', direction = 'asc', keyword = '', forceRefresh = false) {
    dfcmCurrentTable = tableName;
    dfcmCurrentPage = page;
    dfcmCurrentSize = size;
    dfcmCurrentSort = sort;
    dfcmCurrentDirection = direction;
    dfcmCurrentKeyword = keyword;
    
    // 显示加载中
    const tableDataContainer = document.getElementById('tableDataContainer');
    tableDataContainer.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 高亮选中的表
    document.querySelectorAll('.table-item').forEach(item => {
        item.classList.remove('active');
    });
    document.querySelector(`.table-item[data-table-name="${tableName}"]`)?.classList.add('active');
    
    // 取消之前的请求
    cancelPendingRequests();
    
    // 创建新的AbortController
    dfcmAbortController = new AbortController();
    const signal = dfcmAbortController.signal;
    
    // 检查列信息缓存
    const getColumnsPromise = () => {
        if (!forceRefresh && dfcmCache.columns[tableName]) {
            console.log(`使用缓存的列信息: ${tableName}`);
            return Promise.resolve(dfcmCache.columns[tableName]);
        }
        
        return fetch(`${API_BASE}/dfcmdata/tables/${tableName}/columns`, { signal })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取表结构失败: ' + response.statusText);
                }
                return response.json();
            })
            .then(columns => {
                // 缓存列信息
                dfcmCache.columns[tableName] = columns;
                return columns;
            });
    };
    
    // 检查主键信息缓存
    const getPrimaryKeyPromise = () => {
        if (!forceRefresh && dfcmCache.primaryKeys[tableName]) {
            console.log(`使用缓存的主键信息: ${tableName}`);
            return Promise.resolve(dfcmCache.primaryKeys[tableName]);
        }
        
        return fetch(`${API_BASE}/dfcmdata/tables/${tableName}/primary-key`, { signal })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取主键信息失败: ' + response.statusText);
                }
                return response.text().then(text => {
                    try {
                        return JSON.parse(text);
                    } catch (e) {
                        return text;
                    }
                });
            })
            .then(primaryKey => {
                // 缓存主键信息
                dfcmCache.primaryKeys[tableName] = primaryKey;
                return primaryKey;
            });
    };
    
    // 检查数据缓存
    const getDataPromise = (columns, primaryKey) => {
        const cacheKey = generateCacheKey(tableName, page, size, sort, direction, keyword);
        
        if (!forceRefresh && dfcmCache.data[cacheKey]) {
            console.log(`使用缓存的表数据: ${cacheKey}`);
            return Promise.resolve({
                columns: columns,
                primaryKey: primaryKey,
                data: dfcmCache.data[cacheKey]
            });
        }
        
        const params = new URLSearchParams({
            page: page,
            size: size
        });
        
        if (sort) {
            params.append('sort', sort);
            params.append('direction', direction);
        }
        
        if (keyword) {
            params.append('keyword', keyword);
        }
        
        return fetch(`${API_BASE}/dfcmdata/tables/${tableName}/data?${params}`, { signal })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取表数据失败: ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                // 缓存表数据
                dfcmCache.data[cacheKey] = data;
                
                return {
                    columns: columns,
                    primaryKey: primaryKey,
                    data: data
                };
            });
    };
    
    // 按顺序获取所有数据
    getColumnsPromise()
        .then(columns => {
            // 保存列信息
            dfcmTableColumns[tableName] = columns;
            
            // 获取主键信息
            return getPrimaryKeyPromise().then(primaryKey => {
                // 获取表数据
                return getDataPromise(columns, primaryKey);
            });
        })
        .then(result => {
            // 渲染表格数据
            renderTableData(result.columns, result.primaryKey, result.data);
        })
        .catch(error => {
            // 忽略取消请求的错误
            if (error.name === 'AbortError') {
                console.log('表数据请求已取消');
                return;
            }
            
            console.error('加载表数据失败:', error);
            showMessage('加载表数据失败: ' + error.message, 'error');
            tableDataContainer.innerHTML = '<div class="error-container">加载失败，请刷新重试</div>';
        });
}

/**
 * 渲染表格数据
 */
function renderTableData(columns, primaryKey, data) {
    const tableDataContainer = document.getElementById('tableDataContainer');
    
    // 保存分页信息
    dfcmTablePages[dfcmCurrentTable] = {
        totalElements: data.totalElements,
        totalPages: data.totalPages,
        size: data.size,
        number: data.number
    };
    
    // 构建HTML
    let html = `
        <div class="table-header">
            <h2>${dfcmCurrentTable}</h2>
            <div class="table-actions">
                <div class="search-box">
                    <input type="text" id="dataSearchInput" placeholder="搜索数据..." value="${dfcmCurrentKeyword}">
                    <button onclick="searchTableData()"><i class="fa fa-search"></i></button>
                </div>
            </div>
        </div>
        <div class="table-info">
            <span>列数: <strong>${Object.keys(columns).length}</strong></span>
            <span>行数: <strong>${data.totalElements}</strong></span>
            <span>主键: <strong>${primaryKey || '无'}</strong></span>
        </div>
    `;
    
    // 添加数据表格
    html += `<div class="data-table-wrapper"><table class="data-table"><thead><tr>`;
    
    // 表头
    Object.keys(columns).forEach(columnName => {
        const isSortField = columnName === dfcmCurrentSort;
        html += `<th onclick="sortTableData('${columnName}')">
            ${columnName}
            ${columns[columnName]}
            ${isSortField ? `<i class="fa fa-caret-${dfcmCurrentDirection === 'asc' ? 'up' : 'down'}"></i>` : ''}
        </th>`;
    });
    
    html += '</tr></thead><tbody>';
    
    // 表内容
    data.content.forEach(row => {
        html += '<tr>';
        Object.keys(columns).forEach(columnName => {
            const cellValue = row[columnName] !== null ? row[columnName] : '';
            
            // 处理长文本，限制显示长度
            let displayValue = cellValue;
            if (typeof cellValue === 'string' && cellValue.length > 100) {
                displayValue = cellValue.substring(0, 100) + '...';
            }
            
            html += `<td title="${cellValue}">${displayValue}</td>`;
        });
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    
    // 添加分页控件
    html += `
        <div class="pagination">
            <button onclick="gotoTablePage(0)" ${data.number === 0 ? 'disabled' : ''}>
                <i class="fa fa-angle-double-left"></i>
            </button>
            <button onclick="gotoTablePage(${data.number - 1})" ${data.number === 0 ? 'disabled' : ''}>
                <i class="fa fa-angle-left"></i>
            </button>
            <span>第 ${data.number + 1}/${data.totalPages} 页</span>
            <button onclick="gotoTablePage(${data.number + 1})" ${data.number >= data.totalPages - 1 ? 'disabled' : ''}>
                <i class="fa fa-angle-right"></i>
            </button>
            <button onclick="gotoTablePage(${data.totalPages - 1})" ${data.number >= data.totalPages - 1 ? 'disabled' : ''}>
                <i class="fa fa-angle-double-right"></i>
            </button>
        </div>
    `;
    
    tableDataContainer.innerHTML = html;
}

/**
 * 刷新表数据
 * @param {boolean} forceRefresh - 是否强制刷新数据，不使用缓存
 */
function refreshTableData(forceRefresh = true) {
    loadTableData(dfcmCurrentTable, dfcmCurrentPage, dfcmCurrentSize, dfcmCurrentSort, dfcmCurrentDirection, dfcmCurrentKeyword, forceRefresh);
}

/**
 * 跳转到指定页
 */
function gotoTablePage(page) {
    if (page === dfcmCurrentPage) return; // 避免重复加载相同页
    loadTableData(dfcmCurrentTable, page, dfcmCurrentSize, dfcmCurrentSort, dfcmCurrentDirection, dfcmCurrentKeyword);
}

/**
 * 排序表数据
 */
function sortTableData(sortField) {
    // 切换排序方向
    const direction = (sortField === dfcmCurrentSort && dfcmCurrentDirection === 'asc') ? 'desc' : 'asc';
    loadTableData(dfcmCurrentTable, 0, dfcmCurrentSize, sortField, direction, dfcmCurrentKeyword);
}

/**
 * 搜索表数据
 */
function searchTableData() {
    const searchInput = document.getElementById('dataSearchInput');
    const keyword = searchInput.value.trim();
    
    // 如果关键词未变化，则不重新加载
    if (keyword === dfcmCurrentKeyword) return;
    
    loadTableData(dfcmCurrentTable, 0, dfcmCurrentSize, dfcmCurrentSort, dfcmCurrentDirection, keyword);
}

/**
 * 清理资源，当离开页面或切换到其他模块时调用
 */
function cleanupDfcmResources() {
    cancelPendingRequests();
    
    // 清除定时器
    if (dfcmThrottleTimer) {
        clearTimeout(dfcmThrottleTimer);
        dfcmThrottleTimer = null;
    }
    
    // 可选择性地清理缓存（如果需要释放内存）
    // dfcmCache = { tables: null, columns: {}, primaryKeys: {}, data: {} };
}

// 确保函数在全局范围内可用
window.loadDfcmTables = loadDfcmTables;
window.toggleTableGroup = toggleTableGroup;
window.filterTables = filterTables;
window.loadTableData = loadTableData;
window.throttledLoadTableData = throttledLoadTableData;
window.refreshTableData = refreshTableData;
window.gotoTablePage = gotoTablePage;
window.sortTableData = sortTableData;
window.searchTableData = searchTableData;
window.cleanupDfcmResources = cleanupDfcmResources; 